<template>
  <div class="step2">
    <div class="title">
      <el-icon> <InfoFilled /> </el-icon>{{ $t("reserve.expire") }}
      <span>{{ formDataTime }}</span
      >. {{ $t("reserve.secure") }}.
    </div>
    <div class="form-box" dir="ltr">
      <div class="left">
        <div class="name">{{ $t("reserve.accountInfo") }}</div>
        <div class="form-list">
          <el-form
            :label-position="'top'"
            label-width="auto"
            :model="formLabelAlign"
            :rules="rules"
            ref="formRef"
          >
            <div class="name">{{ $t("reserve.personInfo") }}</div>
            <div class="form">
              <el-form-item :label="$t('reserve.firstName')" prop="firstname">
                <el-input v-model="formLabelAlign.firstname" />
              </el-form-item>
              <el-form-item :label="$t('reserve.lastName')" prop="lastname">
                <el-input v-model="formLabelAlign.lastname" />
              </el-form-item>
              <el-form-item :label="$t('reserve.emailAdd')" prop="email">
                <el-input v-model="formLabelAlign.email" />
              </el-form-item>
              <el-form-item :label="$t('reserve.confirmEmail')" prop="add">
                <el-input v-model="formLabelAlign.add" />
              </el-form-item>
              <!--    <el-checkbox class="check-but" v-model="formLabelAlign.checked" :label="$t('reserve.tips')"
                size="large" /> -->
              <!--     <el-form-item :label="$t('reserve.code')" style="margin:15px 0 0;" prop="zipcode">
                <el-input v-model="formLabelAlign.zipcode" />
              </el-form-item> -->
            </div>
            <div class="name">{{ $t("reserve.contactInfo") }}</div>
            <div class="form">
              <!-- <el-form-item :label="$t('reserve.countryCode')" prop="country_code">
                <el-input v-model="formLabelAlign.country_code" />
              </el-form-item> -->
              <el-form-item :label="$t('reserve.phone')" prop="cellphone">
                <el-input v-model="formLabelAlign.cellphone" />
              </el-form-item>

              <!-- <el-checkbox class="check-but" v-model="formLabelAlign.checked" size="large">
                {{ $t('reserve.tips1') }}
                <span>{{ $t('reserve.viewTerms') }}</span></el-checkbox> -->
            </div>
            <div class="name">{{ $t("reserve.specialiscount") }}</div>
            <div class="form">
              <el-form-item :label="$t('reserve.couponCode')" prop="couponCode">
                <el-input
                  v-model="formLabelAlign.couponCode"
                  @blur="getCheckCoupon"
                  @input="couponChange"
                />
                <span
                  :style="{ color: isCoupon ? 'red' : 'green' }"
                  class="coupon-text"
                  >{{ couponText }}</span
                >
              </el-form-item>
            </div>
            <div class="name">{{ $t("reserve.payType") }}</div>
            <div>
              <ul class="logo-img">
                <!-- tap_payment 支付 -->
                <li
                  v-if="payment_channel.includes('tap_payment')"
                  @click="changeType('tap_payment')"
                  :class="
                    payType === 'tap_payment'
                      ? 'active tap_payment'
                      : 'tap_payment'
                  "
                >
                  <img src="../../../assets/image/tap_payment.png" alt="" />
                </li>
                <!-- sump 支付 -->
                <li
                  v-if="payment_channel.includes('sumup')"
                  @click="changeType('sumup')"
                  :class="payType === 'sumup' ? 'active sumup' : 'sumup'"
                >
                  <img src="../../../assets/image/SumUp_Payment.svg" alt="" />
                </li>
                <!-- cash 支付 -->
                <li
                  v-if="payment_channel.includes('cash')"
                  @click="changeType('cash')"
                  :class="payType === 'cash' ? 'active cash' : 'cash'"
                >
                  <img src="../../../assets/image/cash.png" alt="" />
                </li>
                <!-- paypal 支付 -->
                <li
                  v-if="payment_channel.includes('paypal')"
                  @click="changeType('paypal')"
                  :class="payType === 'paypal' ? 'active paypal' : 'paypal'"
                >
                  <img src="../../../assets/image/paypal.svg" alt="" />
                </li>
                <!-- stripe 支付 -->
                <li
                  v-if="payment_channel.includes('stripe')"
                  @click="changeType('stripe')"
                  :class="payType === 'stripe' ? 'active stripe' : 'stripe'"
                >
                  <img src="../../../assets/image/stripe.png" alt="" />
                </li>
                <!-- midtrans 支付 -->
                <li
                  v-if="payment_channel.includes('midtrans')"
                  @click="changeType('midtrans')"
                  :class="payType === 'midtrans' ? 'active midtrans' : 'midtrans'"
                >
                  <img src="../../../assets/image/midtrans.svg" alt="" />
                </li>
              </ul>
              <p class="pay-text">{{ paymentText(payType) }}</p>
            </div>
          </el-form>
          <div class="fl-row-but">
            <div class="but" @click="prevent">{{ $t("reserve.previous") }}</div>
            <div class="but" @click="next">{{ $t("reserve.commit") }}</div>
          </div>
        </div>
      </div>
      <!-- <div class="right">
        <order :goodPrice="goodPrice" :goodNum="goodNum" :date="date"></order>
      </div> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { checkCoupon } from "../reserve.service";
// import order from "./order.vue"
import { computed, ref, onMounted, watch } from "vue";
import { useI18n } from "vue-i18n";
import { ElMessageBox } from "element-plus";
import {initData} from "@/modules/home/home.service";

const { t } = useI18n();
const couponText = ref("");
const isCoupon = ref();
const emits = defineEmits(["next", "prevent"]);
const props = defineProps([
  "goodPrice",
  "goodNum",
  "date",
  "activeStep",
  "step",
]);
const timer = ref(); // 定时器
const countDown = ref(300);
const formRef = ref();
const formLabelAlign = ref({
  firstname: "",
  lastname: "",
  email: "",
  add: "",
  // checked: false,
  cellphone: "",
  // country_code:'',
  pay_type: "",
  couponCode: "",
});
const payType = ref("");
const payment_channel = ref([]);

watch(
  () => props.activeStep,
  (newMessage, oldMessage) => {
    if (newMessage === props.step && !timer.value) {
      // countDown.value = 300
      startCountDown(); // 执行定时器
    } else {
      // clearInterval(timer.value);
    }
    console.log(newMessage, "newMessage");
  }
);

onMounted(() => {
  getdata()
});

const getdata = () => {
  initData().then((res) => {
    document.title = res.data.store.store_name;
    localStorage.setItem("custom", JSON.stringify(res.data.store.custom));
    localStorage.setItem("store", JSON.stringify(res.data.store));
    payment_channel.value = JSON.parse(
        localStorage.getItem("custom") as any
    ).payment_channel;
    payType.value = payment_channel.value[0];
  });
};

const changeType = (val: string) => {
  payType.value = val;
};

const vailEmail = (rule, value, callback) => {
  if (value == formLabelAlign.value.email) {
    return callback();
  }
  callback(new Error(t("reserve.verifyEmail2")));
};
const rules = ref({
  firstname: [
    { required: true, message: t("reserve.verifyLastName"), trigger: "blur" },
  ],
  lastname: [
    { required: true, message: t("reserve.verifyFirstName"), trigger: "blur" },
  ],
  email: [
    { required: true, message: t("reserve.verifyEmail"), trigger: "blur" },
    {
      type: "email",
      message: t("reserve.verifyEmail3"),
      trigger: ["blur", "change"],
    },
  ],
  add: [
    { required: true, message: t("reserve.verifyEmail2"), trigger: "blur" },
    {
      type: "email",
      message: t("reserve.verifyEmail3"),
      trigger: ["blur", "change"],
    },
    { validator: vailEmail, trigger: ["blur", "change"] },
  ],
  cellphone: [
    { required: true, message: t("reserve.verifyPhone"), trigger: "blur" },
  ],
  // couponCode: [{ required: true, message: t('reserve.verifycouponCode'), trigger: "blur" }]
  // country_code: [{ required: true, message: t('reserve.verifyAreaCode'), trigger: "blur" }]
});

// 检查优惠券是否可用
const getCheckCoupon = async () => {
  if(formLabelAlign.value.couponCode){
    const res = await checkCoupon({
      coupon_code: formLabelAlign.value.couponCode,
    });
    isCoupon.value = res.status;
    couponText.value = res.msg;
    console.log(res, "resssssss");
  }
};

const couponChange = () => {
  if(!formLabelAlign.value.couponCode){
    isCoupon.value = '';
    couponText.value = '';
  }
}

const startCountDown = () => {
  timer.value = setInterval(() => {
    if (countDown.value > 0) {
      countDown.value--;
    } else {
      clearInterval(timer.value);
      ElMessageBox.alert(t("reserve.verifyTimeOut"), t("reserve.prompt"), {
        confirmButtonText: "OK",
        callback: (action: Action) => {
          location.reload();
        },
      });
    }
  }, 1000);
};

const paymentText = (type: String) => {
  const obj = {
    tap_payment: "Tap Payment",
    sumup: "Sumup Payment",
    cash: "Cash Payment ",
    paypal: "Paypal Payment",
    stripe: "Stripe Payment",
    midtrans:"Midtrans Payment"
  };
  return obj[type];
};

const formDataTime = computed(() => {
  const minutes = Math.floor(countDown.value / 60);
  const seconds = countDown.value % 60;
  return `${minutes.toString()}:${seconds.toString().padStart(2, "0")}`;
});

const next = () => {
  formRef.value.validate(async (val) => {
    if (val) {
      await getCheckCoupon()
      if(isCoupon.value !== 1){
        formLabelAlign.value.pay_type = payType.value;
        emits("next", formLabelAlign.value);
      }
    }
  });
};
const prevent = () => {
  emits("prevent");
};
</script>

<style scoped lang="scss">
.step2 {
  padding: 0 10px;
  color: #0e2e57;

  .title {
    position: relative;
    width: 100%;
    padding: 15px;
    border-width: 1px;
    border-style: solid;
    border-radius: 3px;
    font-size: 13px;
    display: flex;
    align-items: center;
    justify-content: center;

    .el-icon {
      margin-right: 5px;
    }

    span {
      color: var(--theme-color);
      font-size: 22px;
      margin: 0 5px;
    }
  }

  .form-box {
    margin: 30px 0;
    display: flex;

    .left {
      width: 100%;
      // width: calc(70% - 15px);
      margin-bottom: 30px;

      .name {
        font-size: 18px;
        font-weight: 600;
        text-align: left;
        margin-bottom: 15px;
      }

      .form-list {
        border-radius: 3px;
        border: 1px solid var(--theme-color);
        padding: 0 15px 15px;

        .name {
          font-size: 16px;
          margin-top: 15px;
        }

        .form {
          flex-wrap: wrap;
          .coupon-text {
            font-size: 12px;
          }

          .el-form-item {
            width: 100%;
            :deep(.el-input__wrapper) {
              background: transparent;
              box-shadow: 0 0 0 1px var(--theme-color) inset;
            }

            :deep(.el-form-item__label) {
              color: #0e2e57;
            }
          }

          .check-but {
            :deep(.el-checkbox__inner) {
              background: transparent;
              border: 1px solid #0e2e57;
            }
            :deep(.el-checkbox__inner::after) {
              border: 1px solid #0e2e57;
              border-left: 0;
              border-top: 0;
            }

            span {
              color: var(--theme-color);
            }
          }
        }

        .but {
          color: #e2e8fc;
          background: var(--theme-color-btn);
          font-size: 14px;
          width: 30%;
          //margin-left: 45px;
          text-align: center;
          cursor: pointer;
          height: 42px;
          line-height: 42px;
          //margin: 0 0 0 auto;
          font-weight: 600;
        }
      }
    }

    .right {
      flex: 1;
      border: 1px solid var(--theme-color);
      border-radius: 3px;
      margin-left: 15px;
    }
  }
}
.fl-row-but {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 30px;
}

.logo-img {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  li {
    color: #0e2e57;
    list-style: none;
    width: 80px;
    height: 60px;
    display: flex;
    align-items: center;
    margin-right: 10px;
    border: 2px solid #999;
    border-radius: 10px;
    margin-bottom: 20px;
    cursor: pointer;
  }
  .tap_payment {
    display: flex;
    justify-content: center;
    img {
      width: 65px;
      // height: 30px;
    }
  }
  .sumup {
    img {
      width: 70px;
      height: 60px;
    }
  }
  .cash {
    img {
      margin: auto;
      width: 40px;
    }
  }
  .paypal {
    img {
      margin: auto;
      width: 65px;
    }
  }

  .stripe {
    img {
      margin: auto;
      width: 60px;
    }
  }

  .midtrans{
    img {
      margin: auto;
      width: 65px;
    }
  }

  .active {
    border-color: var(--theme-color);
  }
}
.pay-text {
  text-align: left;
  margin-bottom: 20px;
  font-size: 14px;
  color: green;
}
</style>